﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace 养老金支付系统
{
    class TextHelper
    {
        /// <summary>
        /// DataTable导出到文本文件，带表头
        /// </summary>
        /// <param name="dt">DataTable对象</param>
        /// <param name="fileName">文件完整路径</param>
        public static void ExportDataTableToTextFile(DataTable dt, string fileName)
        {
            StringBuilder sb = new StringBuilder();
            string title = "";
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                title += dt.Columns[i].ColumnName + ",";
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sb.AppendLine(title);
            foreach (DataRow row in dt.Rows)
            {
                string line = "";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    line += row[i].ToString() + ",";
                }
                line = line.Substring(0, line.Length - 1) + "\n";
                sb.AppendLine(line);
            }
            FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            TextWriter tw = new StreamWriter(fs, Encoding.Default);
            tw.Write(sb.ToString());
            tw.Flush();
            fs.Flush();
            tw.Close();
            fs.Close();
        }
        /// <summary>
        /// DataTable导出到文本文件，不带表头
        /// </summary>
        /// <param name="dt">DataTable对象</param>
        /// <param name="fileName">文件完整路径</param>
        public static void ExportDataTableToTextFileNoTitle(DataTable dt, string fileName)
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataRow row in dt.Rows)
            {
                string line = "";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    line += row[i].ToString() + ",";
                }
                line = line.Substring(0, line.Length - 1) + "\n";
                sb.AppendLine(line);
            }
            FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            TextWriter tw = new StreamWriter(fs, Encoding.Default);
            tw.Write(sb.ToString());
            tw.Flush();
            fs.Flush();
            tw.Close();
            fs.Close();
        }
    }
}
